package com.agileai.miscdp.hotweb.ui.wizards;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.database.DBManager.DataBaseType;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.ui.views.FuncModelTreeView;
import com.agileai.miscdp.server.HotServerManage;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.CryptionUtil;
import com.agileai.util.FileUtil;
/**
 * 创建Hotweb工程向导
 */
public class HotwebProjectWizard extends Wizard implements INewWizard {
	HotwebProjectWizardBasicPage basePage;
	HotwebProjectWizardConfigPage configPage;

	private String projectName = null;
	private String mainPkgPath = null;
	private String driverClass;
	private String driverUrl;
	private String userId;
	private String userPwd;
	private String serverAddress;
	private String serverPort;
	private String projectType;
	private String targetWebPath;
	private String targetSrcPath;
	private String databseType;
	private boolean createWS = false;
	private boolean isServiceProject = false;
	
	
	public HotwebProjectWizard() {
		super();
		setWindowTitle(Messages.getString("AppWizardTitle"));
		setNeedsProgressMonitor(true);
	}
	
	public void addPages() {
		basePage = new HotwebProjectWizardBasicPage(this);
		configPage = new HotwebProjectWizardConfigPage(this);
		addPage(basePage);
		addPage(configPage);
	}
	private boolean isIntegrateProject(){
		return ProjectConfig.ProjectType.IntegrateWebProject.equals(this.projectType);
	}
	public boolean performFinish() {
		this.projectName = basePage.getProjectNameText().getText();
		this.serverAddress = basePage.getServerAddressText().getText();
		this.serverPort = basePage.getServerPortText().getText();
		this.projectType = basePage.isJavaWebProject()
				?ProjectConfig.ProjectType.JavaWebProject:ProjectConfig.ProjectType.IntegrateWebProject;
		this.createWS = basePage.getCreateWSCheckButton().getSelection();
		this.isServiceProject = basePage.serviceWebRadioButton.getSelection();
		
		HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
		try {
			boolean isExistApp = hotServerManage.isExistContext(this.projectName); 
			if (isExistApp){
				MessageDialog.openInformation(getShell(),"提示信息",this.projectName + " is already exists !");
				return false;
			}			
		} catch (Exception e) {
			String errorMsg = e.getLocalizedMessage();
			MessageDialog.openInformation(getShell(),"提示信息",errorMsg);
			return false;
		}			
		
		driverClass = configPage.getDriverClassText().getText();
		driverUrl = configPage.getDriverUrlText().getText();
		userId = configPage.getUserIdText().getText();
		userPwd = configPage.getUserPwdText().getText();
		databseType = configPage.getDataBaseType();
		String[] driverJarPaths = MiscdpUtil.getDriverJarArray(databseType);
		
		this.mainPkgPath = basePage.getMainPackageText().getText();
		if (!basePage.serviceWebRadioButton.getSelection() && !MiscdpUtil.isValidConnection(driverClass,driverUrl,userId,userPwd,driverJarPaths)){
			MessageDialog.openInformation(getShell(),"提示信息","不能连接，请确认数据库连接信息填写正确!");
			return false;
		}
		
		IRunnableWithProgress op = null;
		if (isServiceProject){
			 op = new IRunnableWithProgress() {
					public void run(IProgressMonitor monitor) throws InvocationTargetException {
						try {
							IProject project = createProject(projectName,monitor);
							IJavaProject javaProject = JavaCore.create(project);
							copyServiceWebRoot(javaProject,monitor);
							copyServiceWebCode(javaProject,monitor);
							
							setClasspath(javaProject,monitor);
							String projectPath = project.getLocation().toString();
							createConfig(projectPath,monitor);
							
							boolean isIntegrateApp = ProjectConfig.ProjectType.IntegrateWebProject.equals(projectType);
							createServerContext(isIntegrateApp);						
							project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
						} catch (CoreException e) {
							e.printStackTrace();
							throw new InvocationTargetException(e);
						} finally {
							monitor.done();
						}
					}
				};			
		}else{
			 op = new IRunnableWithProgress() {
					public void run(IProgressMonitor monitor) throws InvocationTargetException {
						try {
							IProject project = createProject(projectName,monitor);
							IJavaProject javaProject = JavaCore.create(project);
							copyResource(javaProject,monitor);
							copySystemCode(javaProject,monitor);
							setClasspath(javaProject,monitor);
							String projectPath = project.getLocation().toString();
							createConfig(projectPath,monitor);
							boolean isIntegrateApp = ProjectConfig.ProjectType.IntegrateWebProject.equals(projectType);
							createServerContext(isIntegrateApp);						
							project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
						} catch (CoreException e) {
							e.printStackTrace();
							throw new InvocationTargetException(e);
						} finally {
							monitor.done();
						}
					}
				};			
		}
		try {
			getContainer().run(true, false, op);
			try {
				IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				IViewPart viewPart = workbenchPage.findView(DeveloperConst.TREE_VIEW_ID);
				if (viewPart != null){
					FuncModelTreeView funcModelTreeView = (FuncModelTreeView)viewPart;
					funcModelTreeView.refreshView();					
				}
			} catch (Exception e) {
				MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(),e);
			}
		} catch (Exception e) {
			MessageDialog.openError(getShell(), "Error", e.getMessage());
			return false;
		}
		return true;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void addBuilder(IProjectDescription projectDescription,String builder) throws CoreException {
	    ArrayList arraylist = new ArrayList();
	    arraylist.addAll(Arrays.asList(projectDescription.getBuildSpec()));
		ICommand icommand = projectDescription.newCommand();
		icommand.setBuilderName(builder);
	    arraylist.add(icommand);
	    projectDescription.setBuildSpec((ICommand[])arraylist.toArray(new ICommand[arraylist.size()]));
	}
	
	private IProject createProject(String name,IProgressMonitor monitor)
		throws CoreException {
		monitor.beginTask("Creating Hotweb Project.....",1000);
		monitor.subTask("create project resouce.....");
		monitor.worked(50);
		try {
			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			IProject project = workspace.getRoot().getProject(name);
			IProjectDescription description = workspace.newProjectDescription(name);
			
			addNature(description,DeveloperConst.JAVA_NATURE_ID);
			addNature(description,DeveloperConst.HOTWEB_NATURE_ID);
			addNature(description,DeveloperConst.JS_NATURE_ID);
			addNature(description,DeveloperConst.FACET_CORE_NATURE_ID);
			addNature(description,DeveloperConst.MODULE_CORE_NATURE_ID);
			addNature(description,DeveloperConst.JAVA_EMF_NATURE_ID);
			
			addBuilder(description,DeveloperConst.JAVA_BUILDER_ID);
			addBuilder(description,DeveloperConst.JAVASCRIPT_VALIDATOR_BUILDER_ID);
			addBuilder(description,DeveloperConst.FACET_CORE_BUILDER_ID);
			addBuilder(description,DeveloperConst.VALIDATION_BUILDER_ID);
			
			project.create(description, new SubProgressMonitor(monitor,1000));
			
			copyWebConfig(project,monitor);
			
			project.open(monitor);
			project.setDescription(description,null);
			return project;
		} catch (final Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			monitor.done();
		}
	}
	
	private void copyServiceWebRoot(IJavaProject javaproject,IProgressMonitor monitor){
		monitor.subTask("copy resource.....");
		monitor.worked(300);
		try {
			String srcWebPath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/jaxws/WebRoot")).getFile();
			String projectPath = javaproject.getProject().getLocation().toString();
			this.targetWebPath = projectPath + "/WebRoot";
			FileUtil.copyDirectory(new File(srcWebPath),new File(targetWebPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void copyServiceWebCode(IJavaProject javaproject,IProgressMonitor monitor)
			throws CoreException {
			monitor.subTask("copy system code.....");
			monitor.worked(300);
			try {
				String targetSrcPath = javaproject.getProject().getLocation().toString()+"/src";
				String mainPkg = this.mainPkgPath.replace(".","/");
				String demoServiceDir = mainPkg + "/" + DeveloperConst.SERVICE + "/demo";
				String systemHandlerDir = mainPkg + "/" + DeveloperConst.CONTROLLER + "/sample";
				String systemServiceDir = mainPkg + "/" + DeveloperConst.BIZMODULER + "/sample";

				FileUtil.createDir(targetSrcPath, systemHandlerDir);
				FileUtil.createDir(targetSrcPath, demoServiceDir);
				FileUtil.createDir(targetSrcPath, systemServiceDir);
				
				Bundle bundle = Platform.getBundle(MiscdpPlugin.getPluginId());

				String demoServicePath = FileLocator.toFileURL(bundle.getResource("resource/jaxws/src/com/companyname/projectname/service/demo")).getFile();
				String systemHandlerPath = FileLocator.toFileURL(bundle.getResource("resource/jaxws/src/com/companyname/projectname/controller/sample")).getFile();
				String systemServicePath = FileLocator.toFileURL(bundle.getResource("resource/jaxws/src/com/companyname/projectname/bizmoduler/sample")).getFile();
				
				File systemHandlerTargetDir = new File(targetSrcPath+"/"+systemHandlerDir);
				File systemServiceTargetDir = new File(targetSrcPath+"/"+systemServiceDir);
				File demoServiceTargetDir = new File(targetSrcPath+"/"+demoServiceDir);
				
				copyDirectory(new File(systemHandlerPath),systemHandlerTargetDir);
				copyDirectory(new File(systemServicePath),systemServiceTargetDir);
				copyDirectory(new File(demoServicePath),demoServiceTargetDir);

				changPkg(demoServiceTargetDir,"com.companyname.projectname",this.mainPkgPath);
				changPkg(systemHandlerTargetDir,"com.companyname.projectname",this.mainPkgPath);
				changPkg(systemServiceTargetDir,"com.companyname.projectname",this.mainPkgPath);
				
				String srcCfgPath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/jaxws/src")).getFile();
				String targetCfgPath = javaproject.getProject().getLocation().toString()+"/src";
				File targetCfgFile = new File(targetCfgPath); 
				copyDirectory(new File(srcCfgPath),targetCfgFile);
				
				FileUtil.createDir(targetCfgPath, "sqlmap");
				String sqlMapPath = FileLocator.toFileURL(bundle.getResource("resource/jaxws/src/sqlmap")).getFile();
				File sqlMapTargetDir = new File(targetSrcPath+"/sqlmap");
				copyDirectory(new File(sqlMapPath),sqlMapTargetDir);
				
				changPkg(targetCfgFile,"com.companyname.projectname",this.mainPkgPath);
				
				String hotwebConfigFile = targetCfgPath+"/"+DeveloperConst.HOTWEB_CONFIG_FILE;
				changJdbcConfig(new File(hotwebConfigFile));
				
				String log4jConfigFile = targetCfgPath+"/"+DeveloperConst.LOG4J_CONFIG_FILE;
				changeLog4jConfig(new File(log4jConfigFile));
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}	
	
	
	private void copyResource(IJavaProject javaproject,IProgressMonitor monitor)
		throws CoreException {
		monitor.subTask("copy resource.....");
		monitor.worked(300);
		try {
			String srcWebPath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/hotweb")).getFile();
			this.targetWebPath = javaproject.getProject().getLocation().toString()+"/WebRoot";
			File targetWebFile = new File(targetWebPath); 
			FileUtil.copyDirectory(new File(srcWebPath),targetWebFile);
			
			String srcCfgPath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/webcfg")).getFile();
			this.targetSrcPath = javaproject.getProject().getLocation().toString()+"/src";
			String targetCfgPath = javaproject.getProject().getLocation().toString()+"/src";
			File targetCfgFile = new File(targetCfgPath); 
			FileUtil.copyDirectory(new File(srcCfgPath),targetCfgFile);
			
			File serviceConfigFile = new File(targetCfgPath+"/"+DeveloperConst.SERVICE_CONFIG_FILE); 
			this.changDbPoolName( serviceConfigFile);

			FileUtil.createDir(targetCfgPath, "sqlmap");
			
			
			File sqlMapTargetDir = new File(targetCfgPath+"/sqlmap");
			if (DataBaseType.MySQL.equals(databseType)){
				String source = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/sqls/sqlmap")).getFile();
				File sourceFile = new File(source);
				copySqlMaps(sourceFile, sqlMapTargetDir);
			}
			else if (DataBaseType.Oracle.equals(databseType)){
				String source = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/sqls/sqlmap4oracle")).getFile();
				File sourceFile = new File(source);
				copySqlMaps(sourceFile, sqlMapTargetDir);
			}
			else if (DataBaseType.SQLServer.equals(databseType)){
				String source = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/sqls/sqlmap4sqlserver")).getFile();
				File sourceFile = new File(source);
				copySqlMaps(sourceFile, sqlMapTargetDir);
			}			
			String hotwebConfigFile = targetCfgPath+"/"+DeveloperConst.HOTWEB_CONFIG_FILE;
			changJdbcConfig(new File(hotwebConfigFile));
			
			String log4jConfigFile = targetCfgPath+"/"+DeveloperConst.LOG4J_CONFIG_FILE;
			changeLog4jConfig(new File(log4jConfigFile));
			
			String targetWebXML = null;
			if (isIntegrateProject()){
				if (createWS){
					String sourceWebXML = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/portlet.web4ws.xml")).getFile();;
					targetWebXML = targetWebPath+"/WEB-INF/web.xml";;
					FileUtil.copyFile(new File(sourceWebXML), new File(targetWebXML));					
				}else{
					String sourceWebXML = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/web.xml")).getFile();;
					targetWebXML = targetWebPath+"/WEB-INF/web.xml";;
					FileUtil.copyFile(new File(sourceWebXML), new File(targetWebXML));	
				}
				String sourcePortletXML = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/portlet.xml")).getFile();;
				String targetPortletXML = targetWebPath+"/WEB-INF/portlet.xml";
				FileUtil.copyFile(new File(sourcePortletXML), new File(targetPortletXML));				
			}else{
				if (createWS){
					String sourceWebXML = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/web4ws.xml")).getFile();;
					targetWebXML = targetWebPath+"/WEB-INF/web.xml";
					FileUtil.copyFile(new File(sourceWebXML), new File(targetWebXML));					
				}
			}
			
			if (createWS){
				String sourceWebXML = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource("resource/JaxWSContext.xml")).getFile();;
				targetWebXML = targetSrcPath+"/JaxWSContext.xml";
				File targetWebXMLFile = new File(targetWebXML);
				FileUtil.copyFile(new File(sourceWebXML), targetWebXMLFile);		
				
			    String content = FileUtil.readFileByLines(targetWebXMLFile.getAbsolutePath(),null);
			    String newContent = content.replace("com.agileai.hotweb", this.mainPkgPath);
			    FileUtil.writeFile(targetWebXMLFile, newContent);
			}
			
			changPkg(targetCfgFile);
			String handlerConfigFile = targetCfgPath+"/" + DeveloperConst.HANDLER_CONFIG_FILE;
			changLoginHandler(new File(handlerConfigFile));

			changMenuHandler(new File(handlerConfigFile));
			changNavigaterHandler(new File(handlerConfigFile));
			
			if (isIntegrateProject()){
				changWebXMLFilterConfig(new File(targetWebXML));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void createServerContext(boolean isIntegrateApp){
		HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
		String docBase = this.targetWebPath;
		
		hotServerManage.createContext(this.projectName, docBase,isIntegrateApp);
	}
	
	private void copySystemCode(IJavaProject javaproject,IProgressMonitor monitor)
		throws CoreException {
		monitor.subTask("copy system code.....");
		monitor.worked(300);
		try {
			String targetSrcPath = javaproject.getProject().getLocation().toString()+"/src";
			String mainPkg = this.mainPkgPath.replace(".","/");
			String indexHandlerDir = mainPkg + "/" + DeveloperConst.CONTROLLER;
			String demoServiceDir = mainPkg + "/" + DeveloperConst.SERVICE + "/demo";
			String systemHandlerDir = mainPkg + "/" + DeveloperConst.CONTROLLER + "/system";
			String systemServiceDir = mainPkg + "/" + DeveloperConst.BIZMODULER + "/system";

			FileUtil.createDir(targetSrcPath, indexHandlerDir);
			FileUtil.createDir(targetSrcPath, systemHandlerDir);
			FileUtil.createDir(targetSrcPath, systemServiceDir);
			
			Bundle bundle = Platform.getBundle(MiscdpPlugin.getPluginId());
			
			String indexHandlerPath = FileLocator.toFileURL(bundle.getResource("resource/syssrc/"+DeveloperConst.INDEX_HANDLER_PATH)).getFile();
			String demoServicePath = FileLocator.toFileURL(bundle.getResource("resource/syssrc/"+DeveloperConst.DEMO_SERVICE_PATH)).getFile();
			String systemHandlerPath = FileLocator.toFileURL(bundle.getResource("resource/syssrc/"+DeveloperConst.SYSTEM_HANDLER_PATH)).getFile();
			String systemServicePath = FileLocator.toFileURL(bundle.getResource("resource/syssrc/"+DeveloperConst.SYSTEM_SERVICE_PATH)).getFile();
			
			File indexHandlerTargetDir = new File(targetSrcPath+"/"+indexHandlerDir);
			
			File systemHandlerTargetDir = new File(targetSrcPath+"/"+systemHandlerDir);
			File systemServiceTargetDir = new File(targetSrcPath+"/"+systemServiceDir);
			
			FileUtil.copyDirectory(new File(indexHandlerPath),indexHandlerTargetDir);
			FileUtil.copyDirectory(new File(systemHandlerPath),systemHandlerTargetDir);
			FileUtil.copyDirectory(new File(systemServicePath),systemServiceTargetDir);

			if (isIntegrateProject()){
				String indexFilterDir = mainPkg + "/" + DeveloperConst.FILTER;
				FileUtil.createDir(targetSrcPath, indexFilterDir);
				File indexFilterTargetDir = new File(targetSrcPath+"/"+indexFilterDir);
				String indexFilterPath = FileLocator.toFileURL(bundle.getResource("resource/syssrc/"+DeveloperConst.INDEX_FILTER_PATH)).getFile();
				FileUtil.copyDirectory(new File(indexFilterPath),indexFilterTargetDir);	
				changPkg(indexFilterTargetDir);
				changIndexFilterPkg(indexFilterTargetDir);
			}

			if (createWS){
				File demoServiceTargetDir = new File(targetSrcPath+"/"+demoServiceDir);
				FileUtil.copyDirectory(new File(demoServicePath),demoServiceTargetDir);
				changServicePkg(demoServiceTargetDir);
			}
			
			changPkg(indexHandlerTargetDir);
			changPkg(systemHandlerTargetDir);
			changPkg(systemServiceTargetDir);
			changIndexHandlerPkg(indexHandlerTargetDir);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void copyWebConfig(IProject project,IProgressMonitor monitor)
		throws CoreException {
		monitor.subTask("copy web config.....");
		monitor.worked(300);
		try {
			copyConfigFile(project,DeveloperConst.JSDTSCOPE_CONFIG_FILE);
			copyConfigFile(project,DeveloperConst.RESOURCES_PREFS_CONFIG_FILE);
			copyConfigFile(project,DeveloperConst.JDT_CORE_PREFS_CONFIG_FILE);
			copyConfigFile(project,DeveloperConst.SUPER_TYPE_CONTAINER_CONFIG_FILE);
			copyConfigFile(project,DeveloperConst.SUPERTYPE_NAME_CONFIG_FILE);
			copyConfigFile(project,DeveloperConst.FACET_CORE_XML_CONFIG_FILE);

			File desWebCfgFile = copyConfigFile(project,DeveloperConst.COMMON_COMPONENT_CONFIG_FILE);
			changWebContext(desWebCfgFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private File copyConfigFile(IProject project,String fileName) throws IOException{
		String targetPath = project.getLocation().toString();
		String filePath = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId())
				.getResource("resource/settings/"+fileName)).getFile();
		File desWebCfgFile = new File(targetPath + "/.settings/" + fileName);
		FileUtil.copyFile(new File(filePath),desWebCfgFile);
		return desWebCfgFile;
	}
	
	public static void copyDirectory(File source,File target) throws IOException {  
	    File[] file = source.listFiles();  
	    for (int i = 0; i < file.length; i++) {  
	        if (file[i].isFile()) {  
	            File sourceTemp = new File(source.getAbsolutePath() + "/"  
	                    + file[i].getName()); 
	            String destPath = target.getAbsolutePath() + "/" + file[i].getName();
	            File destFile = new File(destPath);
	            FileUtil.copyFile(sourceTemp,destFile);
	        }  
	    }
	}
	
	private void changPkg(File dir,String srcPackage,String targetPackage) throws IOException{
		File[] files = dir.listFiles();
		for (int i=0;i < files.length;i++){
			File tempFile = files[i];
			if (tempFile.isDirectory())continue;
		    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
		    String newContent = content.replace(srcPackage, targetPackage);
		    FileUtil.writeFile(tempFile, newContent);
		}
	}
	
	private void changPkg(File dir) throws IOException{
		File[] files = dir.listFiles();
		for (int i=0;i < files.length;i++){
			File tempFile = files[i];
			if (tempFile.isDirectory())continue;
		    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
		    String newContent = content.replace(DeveloperConst.SYS_HANDLER_PACKAGE, this.mainPkgPath+"."+DeveloperConst.CONTROLLER+".system");
		    newContent = newContent.replace(DeveloperConst.SYS_SERVICE_PACKAGE, this.mainPkgPath+"."+DeveloperConst.BIZMODULER+".system");
		    FileUtil.writeFile(tempFile, newContent);
		}
	}
	private void changServicePkg(File dir) throws IOException{
		File[] files = dir.listFiles();
		for (int i=0;i < files.length;i++){
			File tempFile = files[i];
			if (tempFile.isDirectory())continue;
		    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
		    String newContent = content.replace(DeveloperConst.IDX_SERVICE_PACKAGE, this.mainPkgPath+"." + DeveloperConst.SERVICE +".demo");
		    FileUtil.writeFile(tempFile, newContent);
		}
	}
	private void changDbPoolName(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace("Pool_dbname", this.projectName);
	    FileUtil.writeFile(tempFile, newContent);
	}
	private void changLoginHandler(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace(DeveloperConst.IDX_HANDLER_PACKAGE+".LoginHandler", this.mainPkgPath+"."+DeveloperConst.CONTROLLER+".LoginHandler");
	    FileUtil.writeFile(tempFile, newContent);
	}
	private void changMenuHandler(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace(DeveloperConst.IDX_HANDLER_PACKAGE+".MenuTreeHandler", this.mainPkgPath+"."+DeveloperConst.CONTROLLER+".MenuTreeHandler");
	    FileUtil.writeFile(tempFile, newContent);
	}
	private void changNavigaterHandler(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace(DeveloperConst.IDX_HANDLER_PACKAGE+".NavigaterHandler", this.mainPkgPath+"."+DeveloperConst.CONTROLLER+".NavigaterHandler");
	    FileUtil.writeFile(tempFile, newContent);
	}
	
	private void changeLog4jConfig(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace("Hotweb.log",projectName+".log");
	    FileUtil.writeFile(tempFile, newContent);
	}
	
	private void changWebXMLFilterConfig(File tempFile) throws IOException{
	    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
	    String newContent = content.replace(DeveloperConst.IDX_FILTER_PACKAGE+".HotwebUserCasFilter", this.mainPkgPath+"."+DeveloperConst.FILTER+".HotwebUserCasFilter");
	    newContent = newContent.replace("6060", "8080");
	    FileUtil.writeFile(tempFile, newContent);
	}
	
	public static final String CRLF = System.getProperty("line.separator");
	private void changJdbcConfig(File tempFile) throws IOException{
	    StringBuffer content = new StringBuffer();
		BufferedReader reader = null;
		try {
			InputStreamReader read = new InputStreamReader (new FileInputStream(tempFile));
			reader = new BufferedReader(read);
			String tempString = null;

			while ((tempString = reader.readLine()) != null) {
				if (tempString.startsWith(DeveloperConst.DRIVER_CLASS_NAME)){
					content.append(DeveloperConst.DRIVER_CLASS_NAME).append("=");
					content.append(this.driverClass);
				}
				else if (tempString.startsWith(DeveloperConst.URL)){
					content.append(DeveloperConst.URL).append("=");
					content.append(this.driverUrl);
				}
				else if (tempString.startsWith(DeveloperConst.USER_NAME)){
					content.append(DeveloperConst.USER_NAME).append("=");
					content.append(this.userId);
				}
				else if (tempString.startsWith(DeveloperConst.PASSWORD)){
					content.append(DeveloperConst.PASSWORD).append("=");
					String secretKey = getSecurityKey();
					String cryptUserPwd = CryptionUtil.encryption(this.userPwd, secretKey);
					content.append(cryptUserPwd);
				}else{
					content.append(tempString);
				}
				content.append(CRLF);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	    FileUtil.writeFile(tempFile, content.toString());
	}
	public static String getSecurityKey(){
		return "12345678";
	}
	
	private void changIndexHandlerPkg(File dir) throws IOException{
		File[] files = dir.listFiles();
		for (int i=0;i < files.length;i++){
			File tempFile = files[i];
			if (tempFile.isDirectory())continue;
		    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
		    String newContent = content.replace("package "+DeveloperConst.IDX_HANDLER_PACKAGE, "package "+this.mainPkgPath+"."+DeveloperConst.CONTROLLER);
		    FileUtil.writeFile(tempFile, newContent);
		}
	}
	
	private void changIndexFilterPkg(File dir) throws IOException{
		File[] files = dir.listFiles();
		for (int i=0;i < files.length;i++){
			File tempFile = files[i];
			if (tempFile.isDirectory())continue;
		    String content = FileUtil.readFileByLines(tempFile.getAbsolutePath(),null);
		    String newContent = content.replace("package "+DeveloperConst.IDX_FILTER_PACKAGE, "package "+this.mainPkgPath+"."+DeveloperConst.FILTER);
		    FileUtil.writeFile(tempFile, newContent);
		}
	}
	
	private void changWebContext(File tempFile) throws IOException{
		StringWriter writer = new StringWriter();
		FileUtil.writeFile(writer, tempFile);
	    String content = writer.toString();
	    String newContent = content.replace(DeveloperConst.DEFAULT_WEB_CONTEXT, this.projectName);
	    FileUtil.writeFile(tempFile, newContent);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void addNature(IProjectDescription projectDesc,String nature) {
	    ArrayList arraylist = new ArrayList();
	    arraylist.addAll(Arrays.asList(projectDesc.getNatureIds()));
	    arraylist.add(nature);
	    projectDesc.setNatureIds((String[]) arraylist.toArray(new String[arraylist.size()]));
	}
	private void createConfig(String projectPath,IProgressMonitor monitor) 
		throws CoreException{
		monitor.subTask("creating configuration.....");
		monitor.worked(500);
		
		String configFileName = projectPath + "/" + DeveloperConst.PROJECT_CFG_NAME;
		File configFile = new File(configFileName);
		if (!configFile.exists()){
			try {
				configFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ProjectConfig config = new ProjectConfig();
		config.setConfigFile(configFileName);
		config.setDriverClass(driverClass);
		config.setDriverUrl(driverUrl);
		config.setUserId(userId);
		config.setUserPwd(userPwd);
//		config.setClassPathEntry(driverJars);
		config.setMainPkg(mainPkgPath);
		config.setServerAddress(serverAddress);
		config.setServerPort(serverPort);
		config.setProjectType(projectType);
		
		try {
			config.saveHotwebConfig();
			config.addInitFuncTree();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void setClasspath(IJavaProject javaproject,IProgressMonitor monitor)
	        throws JavaModelException, CoreException {
		monitor.subTask("setting project properties.....");
		monitor.worked(400);
		
	    IFolder outputFolder = javaproject.getProject().getFolder(new Path("/WebRoot/WEB-INF/classes"));
	    javaproject.setOutputLocation(outputFolder.getFullPath(), monitor);
		
	    ArrayList arraylist = new ArrayList();
		IFolder sourceFolder = javaproject.getProject().getFolder("/src");
		if (!sourceFolder.exists()){
			sourceFolder.create(true, true,monitor);			
		}
	    arraylist.addAll(Arrays.asList(PreferenceConstants.getDefaultJRELibrary()));
	    
	    int srcIndex = -1;
	    for (int i=0;i < arraylist.size();i++){
	    	IClasspathEntry classpathEntry = (IClasspathEntry)arraylist.get(i);
	    	if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE){
	    		srcIndex = i;
	    		break;
	    	}
	    }
	    if (srcIndex != -1){
	    	arraylist.remove(srcIndex);	    	
	    }
	    arraylist.add(JavaCore.newSourceEntry(new Path("/"+projectName+"/src")));
	    arraylist.add(JavaCore.newContainerEntry(new Path(DeveloperConst.WEB_CONTAINER_ID)));
	    arraylist.add(JavaCore.newContainerEntry(new Path(DeveloperConst.HOTSERVER_CONTAINER_ID)));
	    IClasspathEntry[] cp = (IClasspathEntry[]) arraylist.toArray(new IClasspathEntry[arraylist.size()]);
	    javaproject.setRawClasspath(cp,monitor);
	    IFolder binFolder = javaproject.getProject().getFolder(new Path("bin"));
	    if (binFolder.exists()){
	    	binFolder.delete(true, monitor);
	    }
	}
	
	public void init(IWorkbench workbench, IStructuredSelection selection) {
	}

	private void copySqlMaps(File source,File target) throws IOException{
	    File[] file = source.listFiles();  
	    for (int i = 0; i < file.length; i++) {  
	        if (file[i].isFile()) {  
	            File sourceTemp = new File(source.getAbsolutePath() + "/"+ file[i].getName()); 
	            String destPath = target.getAbsolutePath() + "/" + file[i].getName();
	            File destFile = new File(destPath);
	            FileUtil.copyFile(sourceTemp, destFile);
	        }
	    }
	}
	
	public String getProjectName() {
		return projectName;
	}
	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}
}
